package com.tsing.controller.user;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.tsing.common.result.Result;
import com.tsing.service.CommentsService;
import com.tsing.service.impl.CommentsServiceImpl;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.time.LocalDate;
import java.time.LocalDateTime;

/**
 * @auth 卢孝宇
 * @date 2023/12/15 9:53
 */
public class CommentsController {

    private CommentsService commentsService = new CommentsServiceImpl();
    public Result add(HttpServletRequest request, HttpServletResponse response) throws IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;utf-8");

        // 获取请求体数据
        BufferedReader reader = request.getReader();
        StringBuilder jsonRequest = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            jsonRequest.append(line);
        }

        JSONObject jsonObject = JSON.parseObject(jsonRequest.toString());

        Integer userId = jsonObject.getInteger("userId");
        userId = (userId != null && userId > 0) ? userId : null;

        Integer postId = jsonObject.getInteger("postId");
        postId = (postId != null && postId>0) ? postId : null;

        String comments = (String) jsonObject.get("comments");
        comments = (comments != null && !comments.isEmpty()) ? comments : null;

        String recoveryTime = jsonObject.getString("recoveryTime");
        recoveryTime = (recoveryTime != null && !recoveryTime.isEmpty()) ? recoveryTime : LocalDateTime.now().toLocalDate().toString();

        String address = (String) jsonObject.get("address");
        address = (address != null && !address.isEmpty()) ? address :"湖南";

        Integer likeCount = jsonObject.getInteger("likeCount");
        likeCount = (likeCount != null && likeCount>0) ? likeCount : 0;
//
//        Integer status = jsonObject.getInteger("status");
//        status = (status != null && status>0) ? status : 1;

        Integer list = commentsService.insert(userId,postId,comments,recoveryTime,address,likeCount,1);

        return Result.success(list);
    }
}
